#include "StdAfx.h"
#include "wsHttpTransfer.h"
#include "wsUpdateManager.h"
#include <afxinet.h>

wsHttpTransfer::wsHttpTransfer()
	: totalSize(0), currentSize(0)
{
}


wsHttpTransfer::~wsHttpTransfer()
{
}

bool wsHttpTransfer::ReadText(const TCHAR* url, CString& readString)
{
	CInternetSession mysession;
	//CStdioFile *filedat = NULL;
	CInternetFile* filedat = NULL;

	try
	{
		filedat = (CInternetFile*) mysession.OpenURL(url,1,INTERNET_FLAG_TRANSFER_ASCII);
	}
	catch(CInternetException *e)
	{
		filedat = NULL;
		e->Delete();
	}

	if (filedat)
	{
		//CString line;
		/*for (int i=0; i < 20000 && filedat->ReadString(line); i++)
		{
			readString += line + _T("\\r\\n");
		}*/
		
		char buffer[101];
		UINT br = 0;
		
		while(br = filedat->Read(buffer, 50))
		{
			buffer[br] = 0;
			readString += buffer;
		}

		filedat->Close();
		delete filedat;
		mysession.Close();

		return true;
	}

	return false;
}

bool wsHttpTransfer::DownloadFile(const TCHAR* url, wsUpdateManager* updateManager)
{
	BYTE httpbuff[HTTPBUFLEN] = "\0";
	TCHAR filename[128] = _T("\0");
	
	TRY
	{
		CInternetSession mysession;
		CStdioFile *remotefile = mysession.OpenURL(url,1,INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_DONT_CACHE |INTERNET_FLAG_NO_AUTO_REDIRECT);

		_tcscpy_s(filename, remotefile->GetFileName());
		
		CFile myfile(filename, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
		
		int numbytes = 0;
		this->currentSize = 0;

		while( ( numbytes = remotefile->Read(httpbuff, HTTPBUFLEN) ) )
		{			
			myfile.Write( httpbuff, numbytes );
			this->currentSize += numbytes;
			this->totalSize += numbytes;

			if( updateManager )
			{
				updateManager->progress.currentFileDownSize = this->currentSize;
				updateManager->progress.currentTotalDownSize = this->totalSize;
				updateManager->SendMessageToWindow(wsUpdateManager::MSG_PROGRESS, NULL);
			}
		}

		myfile.Close();		
		remotefile->Close();
		delete remotefile;
		mysession.Close();

		return true;
	}	
	CATCH_ALL(error)
	return false;
	END_CATCH_ALL;
	
	return false;
}

UINT64 wsHttpTransfer::DownloadedTotalSize()
{
	return totalSize;
}

UINT64 wsHttpTransfer::DownloadedCurrentSize()
{
	return currentSize;
}